# Useful io stuff.
# Mark Burnett, March 2008

# Read a dictionary from a file:
def read_dict_float(filename):
    dict = {}
    for line in file(filename).readlines():
        tokens = line.split()
        # Ignore blank lines and full line comments
        if len(tokens) > 0 and tokens[0][0] != "#":
            # put multiple values into a list
            if (len(tokens) > 2 and tokens[2][0] != "#"):
                value_list = []
                for token in tokens[1:]: 
                    if token[0] != '#':
                        value_list.append( float(token) )
                    else:
                        break
                # add the key/value pair to the dictionary
                dict[tokens[0]] = value_list
            else:
                # otherwise put a single value into the value place
                if len(tokens) < 2: # invalid dictionary file
                    raise RuntimeError("Dictionary file corrupted:\n"+line)
                # Everything's ok, add the kv pair
                dict[tokens[0]] = float(tokens[1])
    return dict

# David Morton, April 2008
# write two 3d points to a file -- used in dendritetics debugging
def gnuplot_write_line(file,b,e,axes=0):
    if axes:
        pt = str(" 0\t0\t0\t")
    else:
        pt = str(" ")
    # write the beginging point of the line
    out_string = pt + str(b[0]) + "\t" + str(b[1]) + "\t" + str(b[2]) + "\n"
    file.write(out_string)

    # write the endpoint of the line
    out_string = pt + str(e[0]) + "\t" + str(e[1]) + "\t" + str(e[2]) + "\n\n\n"
    file.write(out_string)

def from_config(variable,config_file="configure"):
    for line in file(config_file).readlines():
        tokens = line.split()
        # Ignore blank lines and full line comments
        if len(tokens) > 0 and tokens[0][0] != "#" and variable == tokens[0]:
            # put multiple values into a list
            if (len(tokens) > 2 and tokens[2][0] != "#"):
                value_list = []
                for token in tokens[1:]: 
                    if token[0] != '#':
                        value_list.append( float(token) )
                    else:
                        break
                # this is what we're looking for, look no more
                return value_list
            else:
                # otherwise put a single value into the value place
                if len(tokens) < 2: # invalid dictionary file
                    raise RuntimeError("Dictionary file corrupted:\n"+line)
                # this is what we're looking for, look no more
                return float(tokens[1])
    raise RuntimeError("Variable named %s not in file %s" %\
                       (variable,config_file))


# read in string info from a config file
def from_config_string(variable,config_file="configure"):
    for line in file(config_file).readlines():
        tokens = line.split()
        # Ignore blank lines and full line comments
        if len(tokens) > 0 and tokens[0][0] != "#":
            # put multiple values into a list
            if (len(tokens) > 2 and tokens[2][0] != "#"):
                value_list = []
                for token in tokens[1:]: 
                    if token[0] != '#':
                        value_list.append( token )
                    else:
                        break
                # if this is what we're looking for, look no more
                if tokens[0] == variable:
                    return value_list
            else:
                # otherwise put a single value into the value place
                if len(tokens) < 2: # invalid dictionary file
                    raise RuntimeError("Dictionary file corrupted:\n"+line)
                # if this is what we're looking for, look no more
                if tokens[0] == variable:
                    return tokens[1]
    raise RuntimeError("Variable not in file")


# read in a text file and convert every line to floats (assumes number of columns same on every row)
def raw_data_columns(filename):
    try:
        file = open(filename,'r')
    except:
        raise RuntimeError("Couldn't open file with filename: %s" % filename)
    data = []
    # read in every line and convert the contents to lists of floats
    for line in file.readlines():
        if line[0] != '#': # ignore comments
            tokens = line.split()
            floats = map(float,tokens)
            # store the list of floats in the data list
            data.append(floats)
    # return the data list
    return data

def list_to_tab_delimited_string(list):
    ''' Turns a list into a tab delimited string '''
    string = str(list[0])
    if len(list) > 1:
        for element in list[1:]:
            string += '\t' + str(element)
    return string
